<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>简易计算器</title>
		<style type="text/css">
			.container {
				width: 400px;
				margin: 150px auto;
				border: 1px solid #000;
				background: cornflowerblue;
			}
			input {
				display: inline-block;
				font-family: "微软雅黑";
				width: 99%;
				font-size: 20px;
			}
		</style>
	</head>

	<body>
		<div class="container">
			<table width="100%" style="text-align:center;">
				<tr>
					<td colspan="3"><input type="text" id="screen" disabled="disabled"/></td> 
					<td><input type="button" value="清除" id="cls"/></td>
				</tr>
				<script type="text/javascript">
					var btnStr = ["789+", "456-", "123*", "0.=/"];
					var html = "";
					for (var i = 0; i < btnStr.length; i++) {
						console.log(btnStr[i]);
						html += "<tr>";
						for (var j = 0; j < btnStr[i].length; j++) {
							html += "<td><input class='btn' type='button' value='";
							html += btnStr[i][j];
							html += "'/></td>";
						}
						html += "</tr>";
					}
					document.write(html);
				</script>
			</table>
		</div>
		<script type="text/javascript">
			var screen = document.getElementById("screen");
			var isNew=true;
			var result=0;//计算结果
			var preOperator='+';//前一次点击的运算符
			document.body.onload = function(){
				var btns = document.getElementsByClassName("btn")
				for (var i in btns) {
					btns[i].onclick = function(e) {
						if ("0123456789.".indexOf(this.value)>= 0)//输入数值
						{
							if(isNew==true){//输入数值的第一个符号
								if(preOperator=='='){
									result=0;
									preOperator='+';
								}
								if(screen.value=='0'&&this.value=='0') 
								    return;
								if(this.value=='.')
								    screen.value="0"+this.value;
								else
								    screen.value=this.value;//不是0也不是.的直接替换
								if(screen.value!='0')
								isNew=false;
							}
							else{//输入数值的后续符号
								if(screen.value.indexOf(".")>=0&&this.value==".")
								    return;
								screen.value+=this.value;
							}
						}
						else{//输入运算符
							if(isNew==true){//连续点击运算符
							   preOperator=this.value;
							   return;
							  }
							isNew=true;
							switch(preOperator){
								case"+":
								result+=(screen.value-0);
								break;
								case"-":
								result-=screen.value;
								break;
								case"*":
								result*=screen.value;
								break;
								case"/":
								result/=screen.value;
								break;
							}
							screen.value=result;
							preOperator=this.value;
						}
					}
				}
			}
		    var clear=document.getElementById("cls");
		    clear.onclick=function(){
		    	screen.value="0";
		    	isNew=true;
		    	result=0;
		    	preOperator="+"
		    }
		</script>
	</body>

</html>